<template>
      <div class="work-new-div" v-loading="isLoading">
            <div>
                    <el-tooltip class="item" effect="dark" content="返回" placement="top">
                    <div class="course-back-btn">
                        <router-link to="/course/show/info" class="route-link">
                        <i class="el-icon-back"></i></router-link>
                    </div>
                    </el-tooltip>
            </div>

            <div v-if="isGetInfo">

                <el-form ref="workInfo" :model="workInfo" label-width="100px">
                        
                    <el-form-item label="作业类型：" class="workinfo-item">
                        <el-tag type="danger" effect="plain">类型无法更改</el-tag> <br>
                        
                        <el-radio v-model="workInfo.workType" :label="1" disabled >文本题</el-radio>
                        <el-radio v-model="workInfo.workType" :label="2" disabled >选择题</el-radio>
                    </el-form-item>

                    <el-form-item label="作业名字：" class="workinfo-item">
                        <el-input v-model="workInfo.workName" placeholder="建议使用课后作业-1这样，请不要太长"></el-input>
                    </el-form-item>

                    <el-form-item label="作业分数：" class="workinfo-item">
                        <el-input type="number" v-model="workInfo.workScore" v-if="workInfo.workType == 1"></el-input>
                        <el-tag type="danger" effect="plain"  v-if="workInfo.workType == 2">选择题类型无法修改分数</el-tag>
                    </el-form-item>

                    <el-form-item label="结束时间：" class="workinfo-item">
                        <el-date-picker
                        v-model="workInfo.endTime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        type="datetime"
                        placeholder="选择日期时间">
                        </el-date-picker>
                    </el-form-item>

                    <el-form-item label="题干内容：" >
                        <el-radio v-model="workInfo.contentType" :label='1'>上传文本</el-radio>
                        <el-radio v-model="workInfo.contentType" :label='2'>上传图片</el-radio>

                        <editor :content='workInfo.content' @editorContent="getContent"  v-if="workInfo.contentType == 1"></editor>
                        <el-upload
                                v-if="workInfo.contentType == 2"
                                class="avatar-uploader"
                                action
                                :show-file-list="false"
                                v-model="workInfo.workImgUrl"
                                :before-upload="beforeAvatarUpload"
                                :http-request="getImgPutUrlFromSts"
                                >
                                <img v-if="workInfo.workImgUrl" :src="workInfo.workImgUrl" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>

                    </el-form-item>

                    <el-form-item label="设置选项："  v-if="workInfo.workType == 2">
                        <el-tag type="info">最多支持17个, 如果不够，请联系系统服务者进行添加</el-tag>
                        <br>
                        <el-button style="margin-top:1%;" @click="addCheck">+ 添加选项</el-button>
                        <el-button @click="changeCheckType">{{checkTypeLabel}}</el-button>
                        <el-button @click="changeHalfRight" v-if="workInfo.isMuitlSelect">{{halfRightLabel}}</el-button>
                        <el-tag style="margin-left:2%;" :type="workInfo.startHalfRightGetScore?'success':'danger'" v-if="workInfo.isMuitlSelect">
                            {{workInfo.startHalfRightGetScore?'已开启半对得分':'已关闭半对得分'}}
                        </el-tag>
                        
                        <div class="work-check-item" id="checkinfo">
                                <div  v-for="checkinfo,index in workInfo.checkInfos" 
                                :key="index" style="margin-top:1%;">

                                    <div class="work-check-label">{{checkinfo.label}} :</div> 
                                    <el-input class="check-input" v-model="checkinfo.content"></el-input>
                                    <el-radio style="margin-left:2%;" border 
                                    v-if="!workInfo.isMuitlSelect"
                                    @change="changeTheTrueCheck(checkinfo.label)"
                                    v-model="workInfo.trueCheck" :label='checkinfo.label'>设为正确答案</el-radio>

                                    <el-checkbox border style="margin-left:2%" 
                                    v-if="workInfo.isMuitlSelect"
                                    :label='checkinfo.label' v-model="workInfo.checkList">设为正确答案</el-checkbox>
                                </div>

                        </div>


                    </el-form-item>
                    <el-form-item>
                        <el-button @click="updateTheWork" type="primary">修改</el-button>
                        <el-tooltip class="item" effect="dark" content="删除该作业" placement="right">
                            <el-button type="danger" icon="el-icon-delete"  plain></el-button>
                        </el-tooltip>
                    </el-form-item> 
                </el-form>
          </div>
          

    </div>
</template>

<script>
import Editor from '../../components/Editor.vue'
import * as API from '../../api/work/index'
import * as FILEAPI from '../../api/file/index'
import UUID from 'uuidjs';

export default {

  components: { Editor },
    data() {
        return {
            isLoading:true,
            isGetInfo:false,
            checkLabels:['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 
                        'K', 'L', 'M', 'N', 'O', 'P', 'Q'],
            checkLabelIndex: -1,
            checkTypeLabel:"切换为多选",
            halfRightLabel:'开启半对得分',
            workInfo: {
                workName:"",
                workScore: 5,
                workType: 1, //1是文本，2是选择
                contentType: 1,
                isMuitlSelect:false,
                content: "",
                trueCheck:'A',
                endTime:"",
                workImgUrl:"",
                startHalfRightGetScore: false,
                checkList:['A'],
                checkInfos:[
                    {label:"A", 'content':'', isTrueCheck:true}
                ],
                workId:'',
            }
        }
    },
    methods: {
        changeTheTrueCheck(label){
            console.log(label)
            this.workInfo.checkInfos.forEach(checkInfo => {
                if(checkInfo.label === label) {
                    checkInfo.isTrueCheck = true
                    return
                }else {
                     checkInfo.isTrueCheck = false
                }
            })
        },
        getTrueCheck(checkInfos, isMuitlSelect) {
            if(isMuitlSelect) {
                let checkList = []
                checkInfos.forEach(checkInfo => {
                    this.checkLabelIndex++;
                    if(checkInfo.isTrueCheck === true) {
                        checkList.push(checkInfo.label)
                    }
                })
                this.workInfo.checkList = checkList
            }else {
                checkInfos.forEach(checkInfo => {
                    this.checkLabelIndex++;
                    if(checkInfo.isTrueCheck === true) {
                        this.workInfo.trueCheck = checkInfo.label
                        return
                    }
                })
            }
        },
        addCheck() {
            let newLabel = this.checkLabels[++this.checkLabelIndex]
            this.workInfo.checkInfos.push(
                {
                    label: newLabel,
                    content: "",
                    isTrueCheck: false,
                }
            )
        },
        updateTheWork() {
            API.updateTheWork(this.workInfo).then(res => {
                if(res.code == 200) {
                    this.$message({
                        message: '修改成功',
                        type: 'success'
                    });
                }else {
                    this.$message.error('修改失败');
                }
            }).catch(err => {
                console.log(err)
                this.$message.error('网络不太好'+ err);
            })
        },
        getContent(data) {
            this.workInfo.content = data
        },
        handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isPNG = file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG && !isPNG) {
                this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return (isJPG || isPNG) && isLt2M;
        },
        getImgPutUrlFromSts(option) {
            let fileName = UUID.generate()
            let fileType = option.file.type.split("/")[1]
            FILEAPI.getImgUrl(fileName, fileType).then(res => {

                let url = res.data.URL

                const oReq = new XMLHttpRequest();
                oReq.open('PUT', url, true);
                oReq.setRequestHeader("Content-Type", "application/octet-stream")
                oReq.setRequestHeader("x-oss-meta-author", "nothing")
                oReq.send(option.file);
                oReq.onload = () => {
                    this.workInfo.workImgUrl = `https://nothing-link.oss-cn-beijing.aliyuncs.com/${fileName}.${fileType}`;
                };
            }).catch((error) => {
                this.$notify.error({
                    title: '网路错误，或者服务器宕机',
                    message: error,
                });
            });
        },
        changeCheckType() {
            if(this.workInfo.isMuitlSelect) {
                this.workInfo.isMuitlSelect = false
                this.checkTypeLabel = '切换为多选'
            }else {
                this.workInfo.isMuitlSelect = true
                this.checkTypeLabel = '切换为单选'
            }
        },
        changeHalfRight() {
            if(this.workInfo.startHalfRightGetScore) {
                this.workInfo.startHalfRightGetScore = false
                this.halfRightLabel = '开启半对得分'

            }else {
                //当前状态为
                this.workInfo.startHalfRightGetScore = true

                this.halfRightLabel = '关闭半对得分'
            }
        },
        getWorkInfoByID() {
            API.getWorkInfoByID(this.workInfo.workId).then(res => {
                if(res.code == 200) {
                    this.workInfo = res.data.work
                    
                    //判断是不是选择题
                    if(this.workInfo.workType == 2) {
                        let checkInfos = JSON.parse(this.workInfo.checkInfos)
                        
                        this.workInfo.checkInfos = checkInfos.checkItem
                        this.getTrueCheck(this.workInfo.checkInfos, false)
                        this.workInfo.isMuitlSelect = checkInfos.isMuitlSelect
                        
                        //判断是不是多选题
                        if(checkInfos.isMuitlSelect) {
                            
                            this.getTrueCheck(this.workInfo.checkInfos, true)
                            //获取是否开启半对的信息。
                            this.workInfo.startHalfRightGetScore = checkInfos.isStartHalfRightGetScore
                            
                            this.checkTypeLabel = '当前为多选'
                            if(this.workInfo.startHalfRightGetScore) {
                                this.halfRightLabel = '关闭半对得分'
                            }else {
                                this.halfRightLabel = '开启半对得分'
                            }
                        }else {
                            this.checkTypeLabel = '当前为单选'
                        }
                    }else {
                        this.workInfo.checkInfos = []
                    }

                }else {
                    this.$message.error(res.data.error);
                }
                this.isGetInfo = true
                this.isLoading = false
                
            }).catch(err => {
                console.log(err)
                this.$message.error('网络不太好'+ err);
            })
        }
    },
    mounted() {
        if(this.$route.params.workId == undefined) {
            this.$router.push({
                path:"/course/show/info"
            })

        }else {
            this.workInfo.workId = this.$route.params.workId
            this.getWorkInfoByID()
        }
    }
}
</script>

<style>
.work-check-label {
    display:inline-block;
    width: 20px;
}

</style>